package org.mobile.api.logger;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.mobile.model.util.Constants;
import org.mobile.model.util.DataUtil;
import org.mobile.model.util.DateUtil;
import org.mobile.model.util.ServiceUtil;

import net.sf.json.JSONObject;

import com.ucmed.api.logger.AbsApiLogger;


public abstract class AbsLocalApiLogger extends AbsApiLogger {

	protected abstract void addDateToMap(Map<String, Object> map,
			String userId, JSONObject req);

	@Override
	public void log(String userId, JSONObject req) {
		Map<String, Object> map = new HashMap<String, Object>();
		addDateToMap(map, userId, req);
		JSONObject apiFlowJnl = new JSONObject();
		apiFlowJnl.put("clientUser", userId);
		if (userId == null) {
			apiFlowJnl.put("clientUser",req.optString("user_id"));
		}
		addDateToModel(apiFlowJnl, map, req);
		//ApiFlowJnlModel model = new ApiFlowJnlModel();
		//((ApiFlowJnlService) service).addApiFlowJnl(model);
		ServiceUtil.doService("apiflowJnlService", "addApiFlowJnl", apiFlowJnl);
	}

	private void addDateToModel(JSONObject apiFlowJnl, Map<String, Object> map,
			JSONObject req) {
		//JSONObject params = req.optJSONObject(Constants.PARAMS);
		Calendar calendar = Calendar.getInstance();
		apiFlowJnl
				.put("clientChannel", req.optString(Constants.CLIENT_CHANNEL));
		apiFlowJnl.put("clientDate", DateUtil.getyyyyMMdd(calendar.getTime()));
		apiFlowJnl.put("clientDatetime", calendar.getTime());
		apiFlowJnl.put("clientMobile", req.optString(Constants.CLIENT_MOBILE));
		apiFlowJnl.put("clientMobileSdk",
				req.optString(Constants.CLIENT_MOBILE_SDK));
		apiFlowJnl.put("clientMobileType",
				req.optString(Constants.CLIENT_MOBILE_TYPE));
		apiFlowJnl.put("clientMobileVersion",
				req.optString(Constants.CLIENT_MOBILE_VERSION));
		apiFlowJnl.put("clientTransname",
				req.optString(Constants.CLIENT_TRANSNAME));
		String data = req.toString();
		apiFlowJnl.put("data", data);
		apiFlowJnl.put("day",
				((Integer) calendar.get(Calendar.DAY_OF_MONTH)).toString());
		apiFlowJnl.put("hour",
				((Integer) calendar.get(Calendar.HOUR_OF_DAY)).toString());
		//apiFlowJnl.put("ip", params.optString(Constants.IP));
		apiFlowJnl.put("month",
				((Integer) (calendar.get(Calendar.MONTH) + 1)).toString());
		apiFlowJnl.put("year",
				((Integer) calendar.get(Calendar.YEAR)).toString());
		// apiFlowJnl.put("clientUser", params.optString("user_id"));
		//apiFlowJnl.put("hospitalId", params.optInt("hospitalId"));

		apiFlowJnl.put("paramId", DataUtil.getLongValue(map, "id"));
		apiFlowJnl.put("tmp1", getValue(map.get(Constants.TMP1)));
		apiFlowJnl.put("tmp2", getValue(map.get(Constants.TMP2)));
		apiFlowJnl.put("tmp3", getValue(map.get(Constants.TMP3)));
		apiFlowJnl.put("tmp4", getValue(map.get(Constants.TMP4)));
		apiFlowJnl.put("tmp5", getValue(map.get(Constants.TMP5)));
	}
	
	private String getValue(Object value){
		return value==null?null:value.toString();
	}
}
